package cn.iocoder.yudao.module.bpm.service.sourceapply;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.controller.admin.sourceapply.vo.SourceApplyPageReqVO;
import cn.iocoder.yudao.module.bpm.controller.admin.sourceapply.vo.SourceApplySaveReqVO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.source.SourceDO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.sourceapply.SourceApplyDO;
import cn.iocoder.yudao.module.bpm.dal.dataobject.sourceapplydetail.SourceApplyDetailDO;
import cn.iocoder.yudao.module.bpm.dal.mysql.source.SourceMapper;
import cn.iocoder.yudao.module.bpm.dal.mysql.sourceapply.SourceApplyMapper;
import cn.iocoder.yudao.module.bpm.dal.mysql.sourceapplydetail.SourceApplyDetailMapper;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceStatusEnum;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.OA_LEAVE_NOT_EXISTS;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.SOURCE_APPLY_NOT_EXISTS;

/**
 * 资源申请 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class SourceApplyServiceImpl implements SourceApplyService {

    public static final String PROCESS_KEY = "sourceapply";

    @Resource
    private SourceApplyMapper sourceApplyMapper;

    @Resource
    private SourceApplyDetailMapper sourceApplyDetailMapper;

    @Resource
    private SourceMapper sourceMapper;

    @Resource
    private BpmProcessInstanceApi processInstanceApi;

    @Override
    public Long createSourceApply(Long userId,SourceApplySaveReqVO createReqVO) {
        // 插入
        SourceApplyDO sourceApply = BeanUtils.toBean(createReqVO, SourceApplyDO.class);
        sourceApplyMapper.insert(sourceApply);

        createSourceApplyDetailList(sourceApply.getId(),createReqVO.getSourceApplyDetails());

        if(createReqVO.getOperateFlag().equals("submit")){
            String processInstanceId = processInstanceApi.createProcessInstance(userId,
                    new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(PROCESS_KEY)
                            //.setVariables(processInstanceVariables)
                            .setBusinessKey(String.valueOf(sourceApply.getId()))
                            .setStartUserSelectAssignees(createReqVO.getStartUserSelectAssignees())).getCheckedData();
            // 将工作流的编号，更新到 OA 请假单中
            sourceApplyMapper.updateById(new SourceApplyDO().setId(sourceApply.getId())
                    .setProcessInstanceId(processInstanceId)
                    .setStatus(BpmProcessInstanceStatusEnum.RUNNING.getStatus()));
        }else {
            sourceApplyMapper.updateById(new SourceApplyDO().setId(sourceApply.getId())
                    .setStatus(BpmProcessInstanceStatusEnum.NOT_START.getStatus()));
        }
        // 返回
        return sourceApply.getId();
    }

    @Override
    public void updateSourceApply(Long userId,SourceApplySaveReqVO updateReqVO) {
        // 校验存在
        validateSourceApplyExists(updateReqVO.getId());
        // 更新
        SourceApplyDO updateObj = BeanUtils.toBean(updateReqVO, SourceApplyDO.class);
        sourceApplyMapper.updateById(updateObj);
        updateSourceApplyDetailList(updateObj.getId(), updateReqVO.getSourceApplyDetails());

        if(updateReqVO.getOperateFlag().equals("submit")){
            String processInstanceId = processInstanceApi.createProcessInstance(userId,
                    new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(PROCESS_KEY)
                            //.setVariables(processInstanceVariables)
                            .setBusinessKey(String.valueOf(updateObj.getId()))
                            .setStartUserSelectAssignees(updateReqVO.getStartUserSelectAssignees())).getCheckedData();
            // 将工作流的编号，更新到 OA 请假单中
            sourceApplyMapper.updateById(new SourceApplyDO().setId(updateObj.getId())
                    .setProcessInstanceId(processInstanceId)
                    .setStatus(BpmProcessInstanceStatusEnum.RUNNING.getStatus()));
        } else {
            sourceApplyMapper.updateById(new SourceApplyDO().setId(updateObj.getId())
                    .setStatus(BpmProcessInstanceStatusEnum.NOT_START.getStatus()));
        }
    }

    @Override
    public void deleteSourceApply(Long id) {
        // 校验存在
        validateSourceApplyExists(id);
        // 删除
        sourceApplyMapper.deleteById(id);

        deleteSourceApplyDetailList(id);
    }

    private void validateSourceApplyExists(Long id) {
        if (sourceApplyMapper.selectById(id) == null) {
            throw exception(SOURCE_APPLY_NOT_EXISTS);
        }
    }

    @Override
    public SourceApplyDO getSourceApply(Long id) {
        return sourceApplyMapper.selectById(id);
    }

    @Override
    public PageResult<SourceApplyDO> getSourceApplyPage(SourceApplyPageReqVO pageReqVO) {
        return sourceApplyMapper.selectPage(pageReqVO);
    }


    private void createSourceApplyDetailList(Long applyId, List<SourceApplyDetailDO> list) {
        if(CollectionUtils.isEmpty(list)) {
            return;
        }
        if (list != null) {
            list.forEach(o -> {
                o.setApplyId(applyId);
                o.setId(null);
            });
        }
        sourceApplyDetailMapper.insertBatch(list);
    }

    private void updateSourceApplyDetailList(Long applyId, List<SourceApplyDetailDO> list) {
        if(CollectionUtils.isEmpty(list)) {
            return;
        }
        sourceApplyDetailMapper.deleteByApplyId(applyId);
        list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createSourceApplyDetailList(applyId, list);
    }

    private void deleteSourceApplyDetailList(Long applyId) {
        sourceApplyDetailMapper.deleteByApplyId(applyId);
    }


    @Override
    public void updateLeaveStatus(Long id, Integer status) {
        validateLeaveExists(id);
        sourceApplyMapper.updateById(new SourceApplyDO().setId(id).setStatus(status));
        if(status.equals(BpmProcessInstanceStatusEnum.APPROVE.getStatus())){
            sourceApplyDetailMapper.getSourceApplyDetailList(id).forEach(o -> {
                sourceMapper.updateById(new SourceDO().setId(o.getSourceId()).setSourceStatus("3"));
            });
        }
    }

    private void validateLeaveExists(Long id) {
        if (sourceApplyMapper.selectById(id) == null) {
            throw exception(OA_LEAVE_NOT_EXISTS);
        }
    }

}